package com.mine.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mine.dao.MineLineMapper;
import com.mine.dao.MineLineOrderMapper;
import com.mine.pojo.LineDataInfo;
import com.mine.pojo.MineLine;
import com.mine.pojo.MineLineExample;
import com.mine.pojo.MineLineOrder;
import com.mine.pojo.MineLineOrderExample;
import com.mine.pojo.MineLineOrderExample.Criteria;
import com.mine.pojo.MineUser;
import com.mine.result.CodeMsg;
import com.mine.result.Result;
import com.sun.tools.classfile.Annotation.element_value;

@Service
public class LineServiceImpl implements LineService {

	@Autowired
	MineLineMapper mineLineMapper;
	
	@Autowired
	MineLineOrderMapper mineLineOrderMapper;
	
	@Autowired
	UserService userService;

	//获取队列详情
	@Override
	public Result getLineDetail(Long lineId, String token) {
		MineUser user = userService.getRedisUserByToken(token);
		if (user==null) {
			return Result.error(CodeMsg.SESSION_ERROR);
		}
		MineLine mineLine = mineLineMapper.selectByPrimaryKey(lineId);
		MineLineOrderExample example = new MineLineOrderExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andUserIdEqualTo(user.getId());
		createCriteria.andLineIdEqualTo(lineId);
		List<MineLineOrder> list = mineLineOrderMapper.selectByExample(example );
		//封装返回数据
		LineDataInfo dataInfo = new LineDataInfo();
		dataInfo.setLine(mineLine);
		if (list.size()!=0) {
			//取第一项
			MineLineOrder mineLineOrder = list.get(0);
			dataInfo.setLineOrder(mineLineOrder);
		}
		
		return Result.success(dataInfo);
	}
	
	//获取队列
	@Override
	public Result getShopLines(Long shopId, String token) {
		//先查询用户信息
		MineUser user = userService.getRedisUserByToken(token);
		if (user==null) {
			return Result.error(CodeMsg.SESSION_ERROR);
		}
		MineLineExample example = new MineLineExample();
		com.mine.pojo.MineLineExample.Criteria criteria = example.createCriteria();
		criteria.andShopIdEqualTo(shopId);
		List<Integer> values = new ArrayList<>();
		//查看该队列 状态 1.正常 2.暂停排队 3.关闭
		values.add(1);
		values.add(2);
		criteria.andStatusIn(values );
		
		List<MineLine> selectByExample = mineLineMapper.selectByExample(example );
		//1.正常排队中 2.已过号 3.正在办理中 4.商家已经暂停排队
		MineLineOrderExample orderexample = new MineLineOrderExample();
		Criteria createCriteria = orderexample.createCriteria();
		createCriteria.andShopIdEqualTo(shopId);
		createCriteria.andUserIdEqualTo(user.getId());
		//该队列申请的所有人
		List<MineLineOrder> list = mineLineOrderMapper.selectByExample(orderexample );
//		Integer count = 0;//正在申请总人数
//		for (int i = 0; i < list.size(); i++) {
//			MineLineOrder order = list.get(i);
//			if (order.getStatus()==1) {
//				count ++;
//			}
//		}
		
		List<LineDataInfo> tmpList = new ArrayList<LineDataInfo>();
		for (int i = 0; i < selectByExample.size(); i++) {
			LineDataInfo tmpDataInfo = new LineDataInfo();
			MineLine mineLine = selectByExample.get(i);
			tmpDataInfo.setLine(mineLine);
			
			for (int j = 0; j < list.size(); j++) {
				
				MineLineOrder lineOrder = list.get(j);
				if (mineLine.getStatus()==2) {//2.暂停排队
					lineOrder.setStatus(4);
				}
				if (mineLine.getId()==lineOrder.getLineId()) {//一个队伍只存在一个在排队人，找到这个排队者
					tmpDataInfo.setLineOrder(lineOrder);
				}
			}
			tmpList.add(tmpDataInfo);
		}

		return Result.success(tmpList);
	}

	//加入到队列中
	@Override
	public Result addShopLine(MineLineOrder lineOrder, String token) {
		//先查询用户信息
		MineUser user = userService.getRedisUserByToken(token);
		if (user==null) {
			return Result.error(CodeMsg.SESSION_ERROR);
		}

		lineOrder.setUserId(user.getId());
		
		//先查询排队者是否已经加入该队列
		MineLineOrderExample example = new MineLineOrderExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(user.getId());
		criteria.andLineIdEqualTo(lineOrder.getLineId());
		criteria.andShopIdEqualTo(lineOrder.getShopId());
		criteria.andStatusEqualTo(1);
		List<MineLineOrder> list = mineLineOrderMapper.selectByExample(example );
		if (list.size()>0) {
			return Result.error("您已经排队!");
		}
		//未加入到队列
		//获取当前排队信息
		MineLine byPrimaryKey = mineLineMapper.selectByPrimaryKey(lineOrder.getLineId());
		if (byPrimaryKey==null) {
			return Result.error("要加入的队列不存在！");
		}
		//查看该队列 状态 1.正常 2.暂停排队 3.关闭
		if (byPrimaryKey.getStatus()!=null&&byPrimaryKey.getStatus()==2) {
			return Result.error("商家已经暂停排队，如有疑问，请联系商家！");
		}
		if (byPrimaryKey.getStatus()!=null&&byPrimaryKey.getStatus()==3) {
			return Result.error("商家已经关闭排队！");
		}
		
		//添加到队列中
		//设置当前排队号码 
		String number = "";
		String currentNumber = byPrimaryKey.getCurrentNumber();
		Long lineId = lineOrder.getLineId();
		if (currentNumber==null||byPrimaryKey.getCurrentTotalCount()==0||currentNumber.trim().equals("")) {//第一个加入队列 之前没有
			number = getLetter(lineId.intValue()) +"0001";
		}else {
			//查询队列信息
			MineLineOrderExample orderExample = new MineLineOrderExample();
			orderExample.setOrderByClause("number ASC");
			Criteria createCriteria = orderExample.createCriteria();
			createCriteria.andShopIdEqualTo(lineOrder.getShopId());
			createCriteria.andStatusEqualTo(1);
			createCriteria.andLineIdEqualTo(lineOrder.getLineId());
			//System.out.println("111");
			List<MineLineOrder> selectByExample = mineLineOrderMapper.selectByExample(orderExample );
			if (selectByExample.size()==0) {
				//没有人排队
				currentNumber = getLetter(lineId.intValue()) +"0001";
			}else{
				//有人排队 获取最后一个排队者序号
				MineLineOrder mineLineOrder = selectByExample.get(selectByExample.size()-1);
				
				currentNumber = mineLineOrder.getNumber();
			}
			
//			if (currentNumber==null) {
//				currentNumber = getLetter(lineId.intValue()) +"0001";
//			}
			//已经有人加入到队列中 获取号码
			String headS = currentNumber.substring(0, 1);
			String aferS = currentNumber.substring(1);
			Integer parseInt = Integer.parseInt(aferS);
			//在前一个数前加1
			Integer countInteger = parseInt +1;
			if (countInteger<10) {
				number = headS +"000"+countInteger;
			}else if (countInteger>10&&countInteger<100) {
				number = headS + "00"+countInteger;
			}else if(countInteger>100&&countInteger<1000){
				number = headS +"0"+ countInteger;
			}else {
				number = headS + countInteger;
			}
		}
		//更新队列类目信息
		MineLine record = new MineLine();
		record.setId(lineOrder.getLineId());
		record.setCurrentTotalCount(byPrimaryKey.getCurrentTotalCount()+1);
		if (currentNumber==null||byPrimaryKey.getCurrentTotalCount()==0) {//第一个加入队列 之前没有
			record.setCurrentNumber(number);
		}
		mineLineMapper.updateByPrimaryKeySelective(record);
		
		//更新队列信息
		lineOrder.setNumber(number);
		lineOrder.setCreateTime(new Date());
		if (currentNumber==null||byPrimaryKey.getCurrentTotalCount()==0) {//第一个加入队列 之前没有
			lineOrder.setStatus(3);
		}
		mineLineOrderMapper.insertSelective(lineOrder);
		
		return Result.ok();
	}
	
	private String getLetter(Integer index){
		
		List<String> list = Arrays.asList("A","B","C","D","E","F","G","H","I","J");
		if (index>10) {
			index = index%10;
		}
		return list.get(index);
	}

	@Override
	public Result updateShopLine(MineLine line, String token) {
		//先查询用户信息
		MineUser user = userService.getRedisUserByToken(token);
		if (user==null) {
			return Result.error(CodeMsg.SESSION_ERROR);
		}
		if (line.getStatus()==null||line.getId()==null) {
			return Result.error(CodeMsg.BIND_ERROR);
		}
//		//1.正常排队中 2.已过号 3.正在办理中 4.商家已经暂停排队 
//		if (line.getStatus()==3||line.getStatus()==2) {//关闭排队 状态 1.正常 2.暂停排队 3.关闭
//			MineLineOrder record = new MineLineOrder();
//			record.setStatus(4);//'状态 1.正常排队中 2.已过号 3.正在办理中 4.商家已经暂停排队 
//			MineLineOrderExample example = new MineLineOrderExample();
//			Criteria createCriteria = example.createCriteria();
//			createCriteria.andLineIdEqualTo(line.getId());//更新该队列下的所有排队
//			
//			mineLineOrderMapper.updateByExampleSelective(record, example );
//		}
		mineLineMapper.updateByPrimaryKeySelective(line);
		
		return Result.ok();
	}

	//管理者创建新队列 
	@Override
	public Result addNewShopLine(MineLine line, String token) {
		//先查询用户信息
		MineUser user = userService.getRedisUserByToken(token);
		if (user==null) {
			return Result.error(CodeMsg.SESSION_ERROR);
		}
		line.setUserId(user.getId());
		line.setCreateTime(new Date());
		mineLineMapper.insertSelective(line);
		return Result.ok();
	}

	@Override
	public Result updateShopLineNext(MineLine line, String token) {
		//先查询用户信息
		MineUser user = userService.getRedisUserByToken(token);
		if (user==null) {
			return Result.error(CodeMsg.SESSION_ERROR);
		}
		//先从队列类目中查处当前轮到号码
		MineLine byPrimaryKey = mineLineMapper.selectByPrimaryKey(line.getId());
		if (byPrimaryKey==null) {
			return Result.error("队列不存在！");
		}
		//先前的轮到号
		String preCurrentNumber = byPrimaryKey.getCurrentNumber();
		//从队列中查询处当前队列数据
		MineLineOrderExample example = new MineLineOrderExample();
		example.setOrderByClause("number DESC");
		Criteria createCriteria = example.createCriteria();
		createCriteria.andLineIdEqualTo(line.getId());
		createCriteria.andStatusEqualTo(1);
		List<MineLineOrder> selectByExample = mineLineOrderMapper.selectByExample(example );
		//查询出的排队人数为0 说明没有人排队了
		if (selectByExample.size()==0) {
			if (preCurrentNumber!=null) {
				MineLineOrder preLineOrder = new MineLineOrder();
				preLineOrder.setStatus(2);
				MineLineOrderExample preExample = new MineLineOrderExample();
				Criteria createCriteria2 = preExample.createCriteria();
				createCriteria2.andNumberEqualTo(preCurrentNumber);
				createCriteria2.andLineIdEqualTo(line.getId());
				mineLineOrderMapper.updateByExampleSelective(preLineOrder, preExample );
				
				//更新队列类目表
				MineLine record = new MineLine();
				record.setId(byPrimaryKey.getId());
				record.setId(line.getId());
				record.setCurrentNumber("");
				record.setCurrentTotalCount(0);
				mineLineMapper.updateByPrimaryKeySelective(record );
			}
			return Result.error("已无排队人员！");
		}
		
		if (preCurrentNumber==null||preCurrentNumber.trim().equals("")) {
			return Result.error("已无人排队人员！");
		}
		
		//获取队列类目中到当前轮到号 更新类目当前轮到号
		MineLineOrder nextLineOrder = selectByExample.get(selectByExample.size()-1);
		//上面做了数组等于0判断 这里可以之前取
		String currentNextNumber = nextLineOrder.getNumber();
		MineLine record = new MineLine();
		record.setId(line.getId());
		record.setCurrentNumber(currentNextNumber);
		record.setCurrentTotalCount(selectByExample.size()-1);
		mineLineMapper.updateByPrimaryKeySelective(record );
		//状态 1.正常排队中 2.已过号 3.正在办理中 4.商家已经关闭排队 
		
		//之前的号设置为已过号
		MineLineOrder newLineOrder1 = new MineLineOrder();
		newLineOrder1.setStatus(2);
		MineLineOrderExample newExample1 = new MineLineOrderExample();
		Criteria createCriteria3 = newExample1.createCriteria();
		createCriteria3.andNumberEqualTo(preCurrentNumber);
		createCriteria3.andLineIdEqualTo(line.getId());
		mineLineOrderMapper.updateByExampleSelective(newLineOrder1, newExample1 );
	
		//当前号设置正在办理
		MineLineOrder newLineOrder = new MineLineOrder();
		newLineOrder.setStatus(3);
		MineLineOrderExample newExample = new MineLineOrderExample();
		Criteria createCriteria2 = newExample.createCriteria();
		createCriteria2.andNumberEqualTo(currentNextNumber);
		createCriteria2.andLineIdEqualTo(line.getId());
		mineLineOrderMapper.updateByExampleSelective(newLineOrder, newExample );

		//重新设置 返回 这里少查一次数据库
		byPrimaryKey.setCurrentTotalCount(selectByExample.size()-1);
		byPrimaryKey.setCurrentNumber(currentNextNumber);
		return Result.success(byPrimaryKey);
	}

	//排队者取消排队
	@Override
	public Result updateCancelShopLines(MineLineOrder lineOrder, String token) {
		MineUser user = userService.getRedisUserByToken(token);
		if (user==null) {
			return Result.error(CodeMsg.SESSION_ERROR);
		}
		//直接删除
		mineLineOrderMapper.deleteByPrimaryKey(lineOrder.getId());
		
		//查询是否是最后一个
		MineLineOrderExample example = new MineLineOrderExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andLineIdEqualTo(lineOrder.getLineId());
		List<Integer> values = new ArrayList<>();
		//查看该队列 状态  1.正常排队中 2.已过号 3.正在办理中 4.商家已经关闭排队
		values.add(1);
		values.add(3);
		createCriteria.andStatusIn(values );
		List<MineLineOrder> list = mineLineOrderMapper.selectByExample(example );
		if (list.size()==0) {//清空排队类目排队号
			MineLine record = new MineLine();
			record.setId(lineOrder.getLineId());
			record.setCurrentNumber("");
			record.setCurrentTotalCount(0);
			mineLineMapper.updateByPrimaryKeySelective(record );
		}
		return Result.ok();
	}

	
	
}
